/**
 * 多模态输入组件
 */
import React, { useState, useRef, useCallback } from 'react';
import {
    View,
    StyleSheet,
    TouchableOpacity,
    Text,
    Image,
    ScrollView,
    StyleProp,
    ViewStyle,
    Platform,
    Modal
} from 'react-native';
import { v4 as uuidv4 } from 'uuid';
import TextInput from '../inputs/TextInput';
import Button from '../common/Button';
import theme from '../../styles/theme';
import globalStyles from '../../styles/global';
import { MultimodalInput as MultimodalInputType } from '../../../api/interfaces/qwen';
import { AudioRecorder } from '../media';

/**
 * 多模态输入组件属性接口
 */
interface MultimodalInputProps {
    /** 提交处理函数 */
    onSubmit?: (input: MultimodalInputType) => void;
    /** 组件样式 */
    style?: StyleProp<ViewStyle>;
    /** 是否禁用 */
    disabled?: boolean;
    /** 是否处于加载状态 */
    loading?: boolean;
    /** 会话上下文ID */
    contextId?: string;
    /** 占位符文本 */
    placeholder?: string;
    /** 提交按钮文本 */
    submitButtonText?: string;
    /** 允许的媒体类型 */
    allowedMedia?: {
        image?: boolean;
        audio?: boolean;
        video?: boolean;
    };
}

/**
 * 多模态输入组件
 */
const MultimodalInput: React.FC<MultimodalInputProps> = ({
    onSubmit,
    style,
    disabled = false,
    loading = false,
    contextId,
    placeholder = '请输入文本或添加图片、音频、视频',
    submitButtonText = '发送',
    allowedMedia = { image: true, audio: true, video: true }
}) => {
    // 状态
    const [text, setText] = useState('');
    const [images, setImages] = useState<Array<File | string>>([]);
    const [audio, setAudio] = useState<Blob | null>(null);
    const [video, setVideo] = useState<File | null>(null);
    const [showAudioRecorder, setShowAudioRecorder] = useState(false);

    // 引用
    const textInputRef = useRef(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const audioInputRef = useRef<HTMLInputElement>(null);
    const videoInputRef = useRef<HTMLInputElement>(null);

    // 打开文件选择器
    const openFilePicker = (type: 'image' | 'audio' | 'video') => {
        if (Platform.OS === 'web') {
            let ref: React.RefObject<HTMLInputElement> | null = null;

            switch (type) {
                case 'image':
                    ref = fileInputRef;
                    break;
                case 'audio':
                    ref = audioInputRef;
                    break;
                case 'video':
                    ref = videoInputRef;
                    break;
            }

            if (ref?.current) {
                ref.current.click();
            }
        } else {
            // 在React Native中使用适当的API
            console.log(`Open ${type} picker on native platform`);
            // 这里将来实现原生平台的媒体选择逻辑
        }
    };

    // 处理图片选择
    const handleImageSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            const newImages = Array.from(files);
            setImages(prev => [...prev, ...newImages]);
        }
        // 重置输入以允许选择相同文件
        if (event.target) {
            event.target.value = '';
        }
    }, []);

    // 处理音频选择
    const handleAudioSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            setAudio(files[0]);
        }
        // 重置输入
        if (event.target) {
            event.target.value = '';
        }
    }, []);

    // 处理视频选择
    const handleVideoSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files && files.length > 0) {
            setVideo(files[0]);
        }
        // 重置输入
        if (event.target) {
            event.target.value = '';
        }
    }, []);

    // 移除图片
    const removeImage = (index: number) => {
        setImages(prev => prev.filter((_, i) => i !== index));
    };

    // 移除音频
    const removeAudio = () => {
        setAudio(null);
    };

    // 移除视频
    const removeVideo = () => {
        setVideo(null);
    };

    // 清空所有输入
    const clearAllInputs = () => {
        setText('');
        setImages([]);
        setAudio(null);
        setVideo(null);
    };

    // 处理音频录制完成
    const handleAudioRecordingComplete = (audioBlob: Blob) => {
        setAudio(audioBlob);
        setShowAudioRecorder(false);
    };

    // 处理音频录制错误
    const handleAudioRecordingError = (error: Error) => {
        console.error('录音错误:', error);
        setShowAudioRecorder(false);
    };

    // 打开音频录制界面
    const openAudioRecorder = () => {
        setShowAudioRecorder(true);
    };

    // 关闭音频录制界面
    const closeAudioRecorder = () => {
        setShowAudioRecorder(false);
    };

    // 处理提交
    const handleSubmit = () => {
        if (disabled || loading || (!text && images.length === 0 && !audio && !video)) {
            return;
        }

        const input: MultimodalInputType = {
            id: uuidv4(),
            text: text || undefined,
            images: images.length > 0 ? images : undefined,
            audio: audio || undefined,
            video: video || undefined,
            timestamp: Date.now(),
            contextId
        };

        onSubmit?.(input);
        clearAllInputs();
    };

    // 渲染已选择的媒体预览
    const renderMediaPreviews = () => {
        return (
            <>
                {/* 图片预览 */}
                {images.length > 0 && (
                    <ScrollView
                        horizontal
                        showsHorizontalScrollIndicator={false}
                        style={styles.mediaPreviewContainer}
                        contentContainerStyle={styles.mediaPreviewContent}
                    >
                        {images.map((image, index) => (
                            <View key={`img-${index}`} style={styles.imagePreview}>
                                <Image
                                    source={{
                                        uri: typeof image === 'string' ? image : URL.createObjectURL(image)
                                    }}
                                    style={styles.previewImage}
                                />
                                <TouchableOpacity
                                    style={styles.removeButton}
                                    onPress={() => removeImage(index)}
                                    disabled={disabled || loading}
                                >
                                    <Text style={styles.removeButtonText}>✕</Text>
                                </TouchableOpacity>
                            </View>
                        ))}
                    </ScrollView>
                )}

                {/* 音频预览 */}
                {audio && (
                    <View style={styles.audioPreview}>
                        <Text style={styles.audioLabel}>
                            {audio instanceof File ? audio.name : '已录制音频'}
                        </Text>
                        <TouchableOpacity
                            style={styles.removeButton}
                            onPress={removeAudio}
                            disabled={disabled || loading}
                        >
                            <Text style={styles.removeButtonText}>✕</Text>
                        </TouchableOpacity>
                    </View>
                )}

                {/* 视频预览 */}
                {video && (
                    <View style={styles.videoPreview}>
                        <Text style={styles.videoLabel}>{video.name}</Text>
                        <TouchableOpacity
                            style={styles.removeButton}
                            onPress={removeVideo}
                            disabled={disabled || loading}
                        >
                            <Text style={styles.removeButtonText}>✕</Text>
                        </TouchableOpacity>
                    </View>
                )}
            </>
        );
    };

    // 渲染媒体选择按钮
    const renderMediaButtons = () => {
        return (
            <View style={styles.mediaButtonsContainer}>
                {allowedMedia.image && (
                    <TouchableOpacity
                        style={styles.mediaButton}
                        onPress={() => openFilePicker('image')}
                        disabled={disabled || loading}
                    >
                        <Text style={styles.mediaButtonIcon}>🖼️</Text>
                    </TouchableOpacity>
                )}

                {allowedMedia.audio && (
                    <>
                        <TouchableOpacity
                            style={styles.mediaButton}
                            onPress={() => openFilePicker('audio')}
                            disabled={disabled || loading}
                        >
                            <Text style={styles.mediaButtonIcon}>🎵</Text>
                        </TouchableOpacity>

                        <TouchableOpacity
                            style={styles.mediaButton}
                            onPress={openAudioRecorder}
                            disabled={disabled || loading}
                        >
                            <Text style={styles.mediaButtonIcon}>🎤</Text>
                        </TouchableOpacity>
                    </>
                )}

                {allowedMedia.video && (
                    <TouchableOpacity
                        style={styles.mediaButton}
                        onPress={() => openFilePicker('video')}
                        disabled={disabled || loading}
                    >
                        <Text style={styles.mediaButtonIcon}>🎬</Text>
                    </TouchableOpacity>
                )}
            </View>
        );
    };

    // Web平台的隐藏文件输入
    const renderHiddenInputs = () => {
        if (Platform.OS !== 'web') return null;

        return (
            <>
                <input
                    type="file"
                    ref={fileInputRef}
                    style={{ display: 'none' }}
                    accept="image/*"
                    multiple
                    onChange={handleImageSelect}
                    disabled={disabled || loading}
                />
                <input
                    type="file"
                    ref={audioInputRef}
                    style={{ display: 'none' }}
                    accept="audio/*"
                    onChange={handleAudioSelect}
                    disabled={disabled || loading}
                />
                <input
                    type="file"
                    ref={videoInputRef}
                    style={{ display: 'none' }}
                    accept="video/*"
                    onChange={handleVideoSelect}
                    disabled={disabled || loading}
                />
            </>
        );
    };

    // 渲染组件
    return (
        <View style={[styles.container, style]}>
            {/* 媒体预览 */}
            {renderMediaPreviews()}

            {/* 输入区域 */}
            <View style={styles.inputContainer}>
                <TextInput
                    ref={textInputRef}
                    value={text}
                    onChangeText={setText}
                    placeholder={placeholder}
                    multiline
                    style={styles.textInput}
                    variant="outlined"
                    disabled={disabled}
                    inputStyle={styles.textInputInner}
                />

                <View style={styles.actionsContainer}>
                    {renderMediaButtons()}

                    <Button
                        title={submitButtonText}
                        onPress={handleSubmit}
                        disabled={disabled || (!text && images.length === 0 && !audio && !video)}
                        loading={loading}
                        size="medium"
                        color="primary"
                        style={styles.submitButton}
                    />
                </View>
            </View>

            {renderHiddenInputs()}

            {/* 音频录制弹窗 */}
            {Platform.OS === 'web' ? (
                <Modal
                    visible={showAudioRecorder}
                    transparent
                    animationType="slide"
                    onRequestClose={closeAudioRecorder}
                >
                    <View style={styles.modalContainer}>
                        <View style={styles.modalContent}>
                            <View style={styles.modalHeader}>
                                <Text style={styles.modalTitle}>录制音频</Text>
                                <TouchableOpacity onPress={closeAudioRecorder}>
                                    <Text style={styles.closeButton}>✕</Text>
                                </TouchableOpacity>
                            </View>

                            <AudioRecorder
                                onRecordingComplete={handleAudioRecordingComplete}
                                onError={handleAudioRecordingError}
                                maxDuration={120} // 限制录音最大时长为2分钟
                            />
                        </View>
                    </View>
                </Modal>
            ) : (
                showAudioRecorder && (
                    <View style={styles.recorderOverlay}>
                        <View style={styles.recorderContainer}>
                            <View style={styles.recorderHeader}>
                                <Text style={styles.recorderTitle}>录制音频</Text>
                                <TouchableOpacity onPress={closeAudioRecorder}>
                                    <Text style={styles.closeButton}>✕</Text>
                                </TouchableOpacity>
                            </View>

                            <AudioRecorder
                                onRecordingComplete={handleAudioRecordingComplete}
                                onError={handleAudioRecordingError}
                                maxDuration={120} // 限制录音最大时长为2分钟
                            />
                        </View>
                    </View>
                )
            )}
        </View>
    );
};

// 样式
const styles = StyleSheet.create({
    container: {
        backgroundColor: theme.colors.background.paper,
        borderTopWidth: 1,
        borderTopColor: theme.colors.divider,
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm
    },
    inputContainer: {
        flexDirection: 'column'
    },
    textInput: {
        borderRadius: theme.borderRadius.md,
        maxHeight: 120
    },
    textInputInner: {
        minHeight: 40,
        maxHeight: 120
    },
    actionsContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginTop: theme.spacing.sm
    },
    mediaButtonsContainer: {
        flexDirection: 'row'
    },
    mediaButton: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: theme.colors.gray[100],
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: theme.spacing.sm
    },
    mediaButtonIcon: {
        fontSize: 16
    },
    submitButton: {
        minWidth: 80
    },
    mediaPreviewContainer: {
        marginVertical: theme.spacing.sm
    },
    mediaPreviewContent: {
        paddingRight: theme.spacing.lg
    },
    imagePreview: {
        width: 80,
        height: 80,
        borderRadius: theme.borderRadius.md,
        marginRight: theme.spacing.sm,
        overflow: 'hidden',
        position: 'relative'
    },
    previewImage: {
        width: '100%',
        height: '100%'
    },
    audioPreview: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: theme.colors.gray[100],
        borderRadius: theme.borderRadius.md,
        padding: theme.spacing.sm,
        marginBottom: theme.spacing.sm
    },
    audioLabel: {
        flex: 1,
        fontSize: theme.typography.fontSize.sm,
        color: theme.colors.text.primary
    },
    videoPreview: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: theme.colors.gray[100],
        borderRadius: theme.borderRadius.md,
        padding: theme.spacing.sm,
        marginBottom: theme.spacing.sm
    },
    videoLabel: {
        flex: 1,
        fontSize: theme.typography.fontSize.sm,
        color: theme.colors.text.primary
    },
    removeButton: {
        width: 20,
        height: 20,
        borderRadius: 10,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        position: 'absolute',
        top: 4,
        right: 4
    },
    removeButtonText: {
        color: theme.colors.common.white,
        fontSize: 12,
        lineHeight: 12
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)'
    },
    modalContent: {
        width: '90%',
        maxWidth: 500,
        backgroundColor: theme.colors.background.default,
        borderRadius: theme.borderRadius.lg,
        padding: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.common.black,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.25,
                shadowRadius: 3.84,
            },
            android: {
                elevation: 5,
            },
            web: {
                boxShadow: theme.shadows.md,
            },
        }),
    },
    modalHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: theme.spacing.md,
    },
    modalTitle: {
        fontSize: theme.typography.fontSize.lg,
        fontWeight: '600',
        color: theme.colors.text.primary,
    },
    closeButton: {
        fontSize: theme.typography.fontSize.lg,
        color: theme.colors.text.secondary,
        padding: theme.spacing.xs,
    },
    recorderOverlay: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    recorderContainer: {
        width: '90%',
        backgroundColor: theme.colors.background.default,
        borderRadius: theme.borderRadius.lg,
        padding: theme.spacing.lg,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.common.black,
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.25,
                shadowRadius: 3.84,
            },
            android: {
                elevation: 5,
            },
        }),
    },
    recorderHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: theme.spacing.md,
    },
    recorderTitle: {
        fontSize: theme.typography.fontSize.lg,
        fontWeight: '600',
        color: theme.colors.text.primary,
    },
});

export default MultimodalInput; 